<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 上传控制类
 * @author wb_wenjie.wuwj <wb_wenjie.wuwj@alibaba-inc.com>
 * @copyright 2013-1-31 yahoo
 */
class Upload extends MY_Controller
{
	function __construct()
	{
		parent::__construct();
		
		// 后台登录验证
		$this->check_login();
		
		// @FIXME 验证权限，前台视图页面有调用，固不加验证
		$this->verify_purview(PURVIEW_UPLOAD);
		
		// 加载语言包
		$this->load->language('upload');
		
		// @TODO 初始化上传设置，可以从数据库中读取配置信息
		
		// 加载上传类的配置文件
		$this->config->load('upload');
		
		// 初始化上传目录，设置为完整的路径
		$config['upload_path'] = dirname(BASEPATH).'/'.$this->config->item('upload_path');
		$this->load->library('upload', $config);
	}
	
	function index()
	{
		$this->show();
	}
	
	/**
	 * 显示上传页面
	 * @param string $type
	 */
	function show($type = 'image', $input = '')
	{
		$data['type'] 	= $type;
		$data['input'] 	= $input;
		$data['header'] = $this->header;
		$this->load->view('upload', $data);
		
	}
	
	/**
	 * 对后台自定义的文件上传处理，即处理非编译器发送的上传请求
	 * 返回json数据
	 */
	function upload_action()
	{
		// 获取上传类型
		$type = $this->input->post('upload_type');
		$form_name = $this->input->post('form_name');
		$form_name = empty($form_name) ? 'file_upload' : $form_name;
		
		// 根据上传类型，限制上传文件的格式和大小，详细配置参照common.php
		$allowed_type = $this->config->item($type, 'upload_allowed');
		$allowed_size = $this->config->item($type . '_size', 'upload_allowed');
		if ($allowed_type && $allowed_size)
		{
			$this->upload->set_allowed_types($allowed_type);
			$this->upload->set_max_filesize($allowed_size);
		}
		
		$result = array('error' => '', 'data' => '');
		if(FALSE == $this->upload->do_upload($form_name))
		{
			$result['error'] = $this->upload->display_errors('', '');
		}
		else
		{
			$data = $this->upload->data();
			$result['data'] = $data['date_folder'] . '/' . $data['file_name'];
		}
		echo json_encode($result);
	}
	
	/**
	 * 处理编辑器发送的上传请求
	 */
	function editor_upload_action()
	{
		// @TODO 增加对文件上传类型的判断
		$result = array('error' => 0, 'message' => '');
		if(FALSE == $this->upload->do_upload('file_upload'))
		{
			$result['error'] = 1;
			$result['message'] = $this->upload->display_errors('', '');
		}
		else
		{
			$data = $this->upload->data();
			//$result['message'] = $data['date_folder'] . '/' . $data['file_name'];
			// @TODO 完善返回路径;处理返回的date_folder为空的情况
			$result['url'] = $this->get_uploadfile_path($data['date_folder'] . '/' . $data['file_name']);
		}
		echo json_encode($result);
	}
}
/* End of file upload.php */
/* Location: ./application/controllers/upload.php */